import React, { useEffect, useState } from 'react';
import router from 'umi/router';
import {
  Table, Modal, Form, Input, Col, message, Select, DatePicker, Row, Button,
} from 'antd';
import moment from 'moment'
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import RenderButtom from '@/components/RenderButton';
import SearchBox from '@/components/SearchBox'
import {
  fetchMessage,
  deleteCollectionWay,
  saveCollectionWay,
  addCollectionWay,
} from '@/services/rentCenter/collection';
import { connect } from 'dva';
import { formItemLayout } from '@/utils/utils';

const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))
const { Option } = Select
const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    align: 'center',
    key: 'index',
  },
  {
    title: '结算单号',
    align: 'center',
    key: 'settlementCode',
    render: params => (
      <span>{params.busReceiveInfo.settlementCode}</span>
    ),
  },
  {
    title: '收款类型',
    align: 'center',
    key: 'fundType',
    render: params => (
      <span>{params.busReceiveInfo.fundType}</span>
    ),
  },
  {
    title: '收款状态',
    align: 'center',
    key: 'statusName',
    render: params => (
      <span>{params.busReceiveInfo.statusName}</span>
    ),
  },
  {
    title: '款项金额（元）',
    align: 'center',
    key: 'sumMoney',
    render: params => (
      <span>{params.busReceiveInfo.sumMoney}</span>
    ),
  },
  {
    title: '计划收款日期',
    align: 'center',
    key: 'planDate',
    render: params => (
      <span>{params.busReceiveInfo.planDate}</span>
    ),
  },
  {
    title: '门店名称',
    align: 'center',
    key: 'storeName',
  },
  {
    title: '提醒号码',
    align: 'center',
    key: 'phone',
  },
  {
    title: '提醒方式',
    align: 'center',
    key: 'remindTypeName',
  },
  {
    title: '发送时间',
    align: 'center',
    key: 'sendTime',
  },
  {
    title: '状态',
    align: 'center',
    key: 'statusName',
  },
];

const receivingListing = props => {
  const { getFieldDecorator } = props.form;
  const [data, setColData] = useState([]);
  const [data2, setColData2] = useState([]);
  const [record, setRecord] = useState([]);
  const [planDate, setplanDate] = useState(null);
  const [collectionWays, setcollectionWays] = useState([]);
  const [staffList, setstaffList] = useState([]);
  const [collectionList, setcollectionList] = useState([]);
  const [listQuery, setListQuery] = useState({
    pageNo: 1,
    pageSize: 10,
  });
  const [info, setInfo] = useState({
    status: 1,
  });
  // 分配\新增角色模态框
  const [isShow, setState] = useState(false);

  // 列表
  const getList = async params => {
    const r = await fetchMessage(params);
    if (r.data && r.data.data) {
      setColData(r.data.data);
    }
  };
  useEffect(() => {
    getList(listQuery);
  }, [listQuery]);

  // 查询
  const searchOneBtn = async params => {
    getList(params);
  };
  // 新增/修改 模态框
  const handleStatus = record => {
    setState(!isShow);
    if (record) {
      setInfo(record)
    }
  };
  const time1 = (v, t) => {
    setplanDate(v)
    setListQuery({ ...listQuery, planDate: t })
  };
  // 查询表单
  const getFields = () => (
    <Col span={18}>
      <Col span={8}>
        <Form.Item label="结算单号">
          <Input onChange={v => { setListQuery({ ...listQuery, condition: v.target.value }) }} placeholder="请输入结算单号" value={listQuery.condition} />
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="款项类型">
          <Select value={listQuery.fundTypeId} onChange={v => { setListQuery({ ...listQuery, fundTypeId: v }) }} placeholder="选择款项类型">
            { collectionList.map((v, i) => (<Option key={v.value}>{v.label}</Option>)) }
          </Select>
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="计划收款日期">
          <DatePicker className="width100" value={planDate} placeholder="请选择计划收款日期" onChange={time1} />
        </Form.Item>
      </Col>
    </Col>
  );
  // 查询表单逻辑
  const handleSearch = e => {
    e.preventDefault()
    searchOneBtn(listQuery);
  };

  const removeRole = async record => {
    deleteCollectionWay({
      id: record.id,
    }).then(res => {
      if (res.data && res.data.code === '0') {
        const index = data.findIndex(e => e.id === record.id);
        setColData(() => {
          data.splice(index, 1);
          return [...data];
        });
      }
    })
  };
  // 表单提交
  const handleSubmit = e => {
    e.preventDefault();
    props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (values.id) {
          saveCollectionWay(values).then(() => {
            getList(listQuery)
            setState(!isShow);
          })
        } else {
          addCollectionWay(values).then(() => {
            getList(listQuery)
            setState(!isShow);
          })
        }
      }
    });
  };
  // 清空查询条件
  const handleReset = () => {
    const aobj = {
      pageNo: 1,
      pageSize: 10,
    }
    setplanDate('')
    setListQuery(aobj)
    getList(aobj)
  };
  // 按钮逻辑
  const handleBtn = type => {
    if (record.length !== 1 && type !== 1) return message.warning('请勾选一条数据！');
    switch (type) {
      // 新增
      case 1:
        return handleStatus();
      // 查询
      case 2:
        return handleSearch();
      case 3:
        return handleStatus(record[0]);
      case 4:
        return removeRole(record[0]);
      case 5:
        router.push({ pathname: '/rentCenter/contractManage/contractDetail', query: { i: record[0].id } });
        break
      default:
        return ''
    }
  };
  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord(selectedRows)
    },
  };
  return (
    <PageHeaderWrapper>
      {/* 查询条件 */}
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Table columns={columns} dataSource={hasSearchBtn ? data : []} rowSelection={rowSelection} rowKey={r => r.id} />
      {/* 新增/修改 */}
      <Modal
        title="发送记录"
        visible={isShow}
        style={{ top: '10%' }}
        width="90%"
        // onOk={handleSubmit.bind(this)}
        onCancel={handleStatus.bind(this)}
        destroyOnClose
      >
        <Table columns={columns} dataSource={data2} rowKey={v => v.id} />
      </Modal>
    </PageHeaderWrapper>
  );
};
export default connect(({ role, global }) => ({
  role,
  hasSearchBtn: global.hasSearchBtn,
}))(Form.create()(receivingListing));
